/*
 * @author: pizigou
 * @date: 2009-11-5
 */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include "task.h"
#include "connect.h"

/**
 * work task for every thread
 */
static void *check_task(void *arg)
{
	int i = 0;
	work_list *p = (work_list *)arg;
	struct timeval t1, t2;
	time_t t;
	struct tm *tm_ptr;
	char time_format[50] = {"\0"};
	char time_format2[50] = {"\0"};
	float f;

	while (p->block && p->block->server[0] !='\0' && i < p->block_num) {
		time(&t);
		tm_ptr = localtime(&t);
		memset(time_format, "\0", 50);
		gettimeofday(&t1,NULL);

		sprintf(time_format, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d,%d", \
							tm_ptr->tm_year + 1900, tm_ptr->tm_mon + 1, tm_ptr->tm_mday, \
							tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec, \
							t1.tv_usec
				);
		connect_probe(p->block);
		//time(&t);
		//tm_ptr = localtime(&t);
		//memset(time_format2, "\0", 50);
		gettimeofday(&t2,NULL);
		/*sprintf(time_format2, "%d-%d-%d %d:%d:%d %dus", \
							tm_ptr->tm_year + 1900, tm_ptr->tm_mon + 1, tm_ptr->tm_mday, \
							tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec, \
							t2.tv_usec
				);
		*/
		//printf("line:%d server:%s,work in thread:%d,state:%d\n", p->block->no, p->block->server, p->tid, p->block->state);
		printf("%s %s %d %s %s %f\n", p->block->server, p->block->port, p->block->state, p->block->http_status, time_format, time_diff(&t1, &t2));
		p->block++;
		i++;
	}
}

/**
 * !! important callback
 * dispatch thread to run task
 */
void dispath_task(block_item *p_item)
{
	int i = 0;
	int n = 0;
	work_list *p;
	int result;
	unsigned int real_thread_num = 0;
	work_list task_list[MAX_THREAD_NUM];

	arg.thread_num = arg.thread_num >= MAX_THREAD_NUM ? MAX_THREAD_NUM : arg.thread_num;

	real_thread_num = p_item->block_num >= arg.thread_num ? arg.thread_num : p_item->block_num; 
	n = p_item->block_num / real_thread_num;
	
	if ( p_item->block_num % real_thread_num != 0 ) {
		n += 1;
		if ( p_item->block_num % n != 0) real_thread_num = p_item->block_num / n + 1;
		else real_thread_num = p_item->block_num / n;
	}

	for (i = 0; i < real_thread_num; i++) {
		p = &task_list[i];
		p->block = p_item->sites + i * n;
		if (i == real_thread_num ) p->block_num = p_item->block_num - i*n;
		else p->block_num = n;
		if (pthread_create(&p->tid, NULL, (void *)check_task, (void *)p) == 0) {
			//printf("create thread tid=%d\n", p->tid);
		} else printf("create thread failed\n");
	}

	for (i = 0; i < real_thread_num; i++) {
		p = &task_list[i];
		if (p && p->tid != 0) {
			if (pthread_join(p->tid, NULL) == 0);
			//else printf("thread:%d end failed\n", p->tid);
		}
	}
}
